package com.smarth.zhizulian.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.smarth.zhizulian.R;
import com.smarth.zhizulian.adapter.VideoAdapter;
import com.smarth.zhizulian.app.BaseConfig;
import com.smarth.zhizulian.app.EventFragment;
import com.smarth.zhizulian.bean.Category;
import com.smarth.zhizulian.bean.Page;
import com.smarth.zhizulian.bean.video.VideoVideoTexts;
import com.smarth.zhizulian.entity.EventBean;
import com.smarth.zhizulian.http.KumaHttp;
import com.smarth.zhizulian.http.exception.NoNetException;
import com.smarth.zhizulian.http.observer.inter.BaseObserver;
import com.smarth.zhizulian.http.utils.RxCompos;
import com.smarth.zhizulian.utils.ACache;
import com.smarth.zhizulian.utils.GsonUtils;
import com.smarth.zhizulian.utils.KumaLog;
import com.smarth.zhizulian.utils.listhelper.RefreshHelper;
import com.smarth.zhizulian.utils.listhelper.impl.model.ListDataModel;
import com.smarth.zhizulian.utils.listhelper.inter.ResponseSender;
import com.smarth.zhizulian.view.LoadingLayout;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by 18865 on 2017/12/21.
 */

public class VideoCategoryFragment extends EventFragment {
    @BindView(R.id.lv_listview)
    ListView lvListview;
    @BindView(R.id.rv_refresh)
    SmartRefreshLayout rv_refresh;
    @BindView(R.id.ll_loadinglayout)
    LoadingLayout llLoadinglayout;
    @BindView(R.id.tv_nonet)
    TextView tvNonet;

    public static final String INTENT_CATEGORY = "INTENT_CATEGORY";
    @BindView(R.id.tv_ongetdata)
    TextView tvOngetdata;

    private Category mCategory;
    private Disposable mDisposable;
    private RefreshHelper<List<VideoVideoTexts>> refreshHelper;
    private VideoAdapter videoAdapter;
    private Disposable mNoNetDisposable;
    private Disposable mOnGetDataDisposable;
    private int randomCoin = 0;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
    }

    @Override
    protected void onCreateView(Bundle savedInstanceState) {
        super.onCreateView(savedInstanceState);
        setBKView(R.layout.fragment_videocategory);
        initListView();
    }

    private void init() {
        mCategory = (Category) getArguments().getSerializable(INTENT_CATEGORY);
    }

    private void initListView() {
        refreshHelper = new RefreshHelper<>(getContext(), llLoadinglayout, rv_refresh);
        refreshHelper.setDataModel(new ListDataModel<List<VideoVideoTexts>>() {
            @Override
            public void fetch(final ResponseSender<List<VideoVideoTexts>> responseSender, int page) {
                KumaHttp.getService().videoReVideoTexts("" + mCategory.getId(), randomCoin, page)
                        .compose(RxCompos.<Page<VideoVideoTexts>>getBECompos())
                        .doOnSubscribe(new Consumer<Disposable>() {
                            @Override
                            public void accept(Disposable disposable) throws Exception {
                                mDisposable = disposable;
                                if (mNoNetDisposable != null && !mNoNetDisposable.isDisposed()) {
                                    KumaLog.kuma("mNoNetDisposable");
                                    mNoNetDisposable.dispose();
                                }
                                if (mOnGetDataDisposable != null && !mOnGetDataDisposable.isDisposed()) {
                                    KumaLog.kuma("mOnGetDataDisposable");
                                    mOnGetDataDisposable.dispose();
                                }
                                try {
                                    tvOngetdata.setVisibility(View.GONE);
                                    tvNonet.setVisibility(View.GONE);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        })
                        .subscribe(new BaseObserver<Page<VideoVideoTexts>>(getContext()) {
                            @Override
                            public void onNext(Page<VideoVideoTexts> vvtPage) {
                                responseSender.sendData(vvtPage.getList());
                                randomCoin = vvtPage.getCount();
                                setmPage(vvtPage.getPageNo());
                                setmMaxPage(vvtPage.getPageNum());
                            }

                            @Override
                            public void onError(Throwable e) {
                                super.onError(e);
                                if (videoAdapter.isDataEmpty()) {
                                    responseSender.sendError((Exception) e);
                                } else {
                                    refreshHelper.finishContent(0);
                                }
                            }

                            @Override
                            public void onErrorNoNet(NoNetException e) {
                                showNoNet();
                            }
                        });
            }
        });
        videoAdapter = new VideoAdapter(getContext(), new ArrayList<>(), mCategory) {
            @Override
            public void onGetData(List profitProfits, boolean isRefresh) {
                super.onGetData(profitProfits, isRefresh);
                if (isRefresh) {
                    showOnGetData(profitProfits.size());
                }
            }
        };
        refreshHelper.setDataAdapter(videoAdapter);
        try {
            String json = ACache.get(getContext()).getAsString(BaseConfig.ACache.VIDEO + mCategory.getName());
            List<VideoVideoTexts> vvtList = GsonUtils.fromJson(json, new TypeToken<List<VideoVideoTexts>>() {
            });
            if (vvtList != null && vvtList.size() > 0) {
                refreshHelper.sendData(vvtList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        refreshHelper.refresh();
    }

    public static VideoCategoryFragment getInstance(Category category) {
        VideoCategoryFragment fragment = new VideoCategoryFragment();
        Bundle args = new Bundle();
        args.putSerializable(INTENT_CATEGORY, category);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mDisposable != null && !mDisposable.isDisposed()) {
            KumaLog.kuma("mDisposable");
            mDisposable.dispose();
        }
//        mCategory = null;
//        mDisposable = null;
//        refreshHelper = null;
//        videoAdapter = null;
//        llLoadinglayout = null;

        if (mNoNetDisposable != null && !mNoNetDisposable.isDisposed()) {
            KumaLog.kuma("mNoNetDisposable");
            mNoNetDisposable.dispose();
        }
        if (mOnGetDataDisposable != null && !mOnGetDataDisposable.isDisposed()) {
            KumaLog.kuma("mOnGetDataDisposable");
            mOnGetDataDisposable.dispose();
        }
    }

    @Override
    protected void onLogin(EventBean eb) {
        refreshHelper.refresh();
    }

    private void showNoNet() {
        Observable.timer(1500, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        mNoNetDisposable = disposable;
                        try {
                            tvNonet.setVisibility(View.VISIBLE);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                })
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        try {
                            tvNonet.setVisibility(View.GONE);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    @Subscriber(tag = "VideoCategoryFragment")
    private void onEvent(EventBean eb) {
        switch (eb.getCode()) {
            case BaseConfig.EventCode.REFRESH:
//                lvListview.smoothScrollToPosition(0);
                lvListview.setSelection(0);
                refreshHelper.refresh();
                break;
        }
    }

    private void showOnGetData(final int num) {
        Observable.timer(1500, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        mOnGetDataDisposable = disposable;
                        try {
                            tvOngetdata.setText("直租链为您推荐" + num + "条更新");
                            tvOngetdata.setVisibility(View.VISIBLE);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                })
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        try {
                            tvOngetdata.setVisibility(View.GONE);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }
}
